package com.julis.html_analyse;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.baseutils.SpfUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.julis.activity.setting.updata.Setting_Remoteupgrade_Activity;
import com.julis.download.Downloader;
import com.julis.init.MAIN;


public class UpdateHelper {

    private static final int MSG_TYPE_UPDATE_NOW = 0; // 立即更新
    private static final int MSG_TYPE_ALREADY_LATEDST_VERSION = 1; // 已经是最新版本



    //创建handler
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_TYPE_UPDATE_NOW:
                    String ipup = (String) SpfUtils.get(context, "ip",
                            MAIN.IP);
                    String portup = (String) SpfUtils.get(context,
                            "port", MAIN.Port);
                    String tempString = "http://" + ipup + ":" + portup;
                    HtmlResultBean htmlResultBean = (HtmlResultBean) msg.obj;
                    Downloader downloader = new Downloader(context,
                            tempString + "/"
                                    + htmlResultBean.getData().getFileName(),
                            htmlResultBean.getData().getFileMd5(), handler);
                    downloader.tryToUpdate("已经检测到新程序", "更新提示");
                    break;
                case MSG_TYPE_ALREADY_LATEDST_VERSION:
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "程序已经是最新版本,无需升级", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    break;
                case 10:
                    Toast.makeText(context, "安裝成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case 11:
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "安裝失败", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    break;
                case 12:
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "签名验证不一致，请联系管理员", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    break;
            }
        }
    };

    Setting_Remoteupgrade_Activity context ;
    public HtmlResultBean getUpdateInfo(Setting_Remoteupgrade_Activity context) {
         this.context = context;


        HtmlResultBean htmlResultBean = new HtmlResultBean();
        InputStream inputStream = null;

        ByteArrayOutputStream arrayOutputStream = null;
        String ipup = (String) SpfUtils.get(context, "ip",
                MAIN.IP);
        String portup = (String) SpfUtils.get(context,
                "port", MAIN.Port);
        String tempString = "http://" + ipup + ":" + portup + "/softversion.html";
        try {
//			String tempString =CodeActivity.map.get("updatePath")
//			+ "/softversion.html";

//			String tempString =CodeActivity.map.get("updatePath")
//					;
            URL url = new URL(tempString);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setConnectTimeout(10 * 1000); // 超时时间
            connection.connect(); // 连接
            int code = connection.getResponseCode();

            if (code == 200) { // 返回的响应码200,是成功.
                inputStream = connection.getInputStream();
                arrayOutputStream = new ByteArrayOutputStream(); // 缓存
                byte[] buffer = new byte[1024 * 10];
                while (true) {
                    int len = inputStream.read(buffer);
                    if (len == -1) {
                        break; // 读取完
                    }

                    arrayOutputStream.write(buffer, 0, len); // 写入
                }
                arrayOutputStream.close();
                inputStream.close();
                String json = arrayOutputStream.toString("GBK");

                Log.d("json", json);
                analysUpdateJson(json, htmlResultBean);
                Log.d("bean:", htmlResultBean.toString());
                downloadAPK(context, htmlResultBean);
            } else if (code == 404) {
                htmlResultBean.setCode(code);
                htmlResultBean.setMsg("服务器错误,页面不存在404");
            } else {
                htmlResultBean.setCode(code);
                htmlResultBean.setMsg("服务器错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            htmlResultBean.setCode(-1);
            htmlResultBean.setMsg("服务器异常,请检查网络," + e.getMessage());

        } finally {
            if (arrayOutputStream != null) {
                try {
                    arrayOutputStream.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                }
            }
        }

        return htmlResultBean;
    }

    private void downloadAPK(Context context,
                             HtmlResultBean htmlResultBean) {
        String appLocalVersion = PackageHelper.getAppVersion(context,
                context.getPackageName());
        //本地版本
        int appLocalVersionInt = Integer.parseInt(appLocalVersion.replace(".",
                ""));
        //服务器版本
        int appServerVersionInt = Integer.parseInt(htmlResultBean.getData()
                .getSoftVersion().replace(".", ""));
        if (appLocalVersionInt >= appServerVersionInt) {
            Log.d("cz", "程序已经是最新版本,无需升级");
            handler.obtainMessage(MSG_TYPE_ALREADY_LATEDST_VERSION)
                    .sendToTarget();
            return;
        }
        Log.d("cz", "准备下载服务器APK");
        handler.obtainMessage(MSG_TYPE_UPDATE_NOW, htmlResultBean)
                .sendToTarget();

    }

    private static void analysUpdateJson(String json,
                                         HtmlResultBean htmlResultBean) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.getInt("code");
            String msg = jsonObject.optString("msg");

            JSONObject jsonObject2 = jsonObject.getJSONObject("data");
            String softVersion = jsonObject2.optString("softVersion");
            String fileName = jsonObject2.optString("fileName");
            String fileMd5 = jsonObject2.optString("fileMd5");

            HtmlResultBean.DATA data = new HtmlResultBean.DATA(softVersion,
                    fileName, fileMd5);
            data.setSoftVersion(softVersion);
            data.setFileName(fileName);
            data.setFileMd5(fileMd5);

            htmlResultBean.setCode(code);
            htmlResultBean.setMsg(msg);
            htmlResultBean.setData(data);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
